/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.recycling.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medusa.gruul.common.core.constant.enums.CommonEnum;
import com.medusa.gruul.common.core.util.ResultPageList;
import com.medusa.gruul.common.data.tenant.ShopContextHolder;
import com.medusa.gruul.common.data.tenant.TenantContextHolder;
import com.medusa.gruul.order.api.enums.OrderStatusEnum;
import com.medusa.gruul.recycling.api.entity.RecyclingAssOrder;
import com.medusa.gruul.recycling.api.entity.RecyclingAssOrderAccount;
import com.medusa.gruul.recycling.mapper.RecyclingAssOrderAccountMapper;
import com.medusa.gruul.recycling.model.dto.SelectStatisticalDto;
import com.medusa.gruul.recycling.model.vo.RecyclingAssOrderAccountStatisticalVo;
import com.medusa.gruul.recycling.model.vo.RecyclingAssOrderListVo;
import com.medusa.gruul.recycling.service.IRecyclingAssOrderAccountService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 基金所得订单用户关联表 服务实现类
 * </p>
 *
 * @author whh
 * @since 2021-05-05
 */
@Service
public class RecyclingAssOrderAccountServiceImpl extends ServiceImpl<RecyclingAssOrderAccountMapper, RecyclingAssOrderAccount> implements IRecyclingAssOrderAccountService {


    @Override
    public ResultPageList<RecyclingAssOrderListVo> recyclingAssOrderAccountList(Integer page, Integer size, String nickName, Integer sortType) {
        Page<RecyclingAssOrderAccount> assOrderAccountPage = this.baseMapper.selectPage(new Page<>(page, size),
                new QueryWrapper<RecyclingAssOrderAccount>()
                        //按昵称查找
                        .like(StrUtil.isNotEmpty(nickName), "nick_name", nickName)
                        //排序方式  1-基金值升序  2-基金值降序   3-按最近交易时间升序  4-按最近交易时间降序
                        .orderByAsc(sortType == 1, "total_fund_quota")
                        .orderByAsc(sortType == 3, "last_pay_time")
                        .orderByDesc(sortType == 2, "total_fund_quota")
                        .orderByDesc(sortType == 4, "last_pay_time")
        );
        List<RecyclingAssOrderAccount> records = assOrderAccountPage.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return new ResultPageList(CommonEnum.SUCCESS_RESPONSE);
        }
        List<RecyclingAssOrderListVo> recyclingAssOrderListVos = records.stream().map(obj -> {
            return BeanUtil.toBean(obj, RecyclingAssOrderListVo.class);
        }).collect(Collectors.toList());
        return new ResultPageList(CommonEnum.SUCCESS_RESPONSE, assOrderAccountPage, recyclingAssOrderListVos);
    }

    @Override
    public void addRecyclingAssOrder(RecyclingAssOrder recyclingAssOrder) {
        RecyclingAssOrderAccount orderAccount = this.baseMapper.selectOne(
                new QueryWrapper<RecyclingAssOrderAccount>().eq("shop_user_id", recyclingAssOrder.getShopUserId())
        );
        if (orderAccount == null) {
            orderAccount = new RecyclingAssOrderAccount();
            orderAccount.setOrderNumber(1);
            orderAccount.setTotalFundQuota(recyclingAssOrder.getFundQuota());
            orderAccount.setTotalAmount(recyclingAssOrder.getPayAmount());
            orderAccount.setShopUserId(recyclingAssOrder.getShopUserId());
        } else {
            orderAccount.setOrderNumber(orderAccount.getOrderNumber() + 1);
            orderAccount.setTotalFundQuota(orderAccount.getTotalFundQuota().add(recyclingAssOrder.getFundQuota()));
            orderAccount.setTotalAmount(orderAccount.getTotalAmount().add(recyclingAssOrder.getPayAmount()));
        }
        //头像及昵称随最后一次的订单更新
        orderAccount.setNickName(recyclingAssOrder.getNickName());
        orderAccount.setAvatarUrl(recyclingAssOrder.getAvatarUrl());

        orderAccount.setLastPayTime(recyclingAssOrder.getCreateTime());
        orderAccount.insertOrUpdate();
    }

    @Override
    public RecyclingAssOrderAccountStatisticalVo recyclingAssOrderAccountStatistical(String shopUserId) {
        RecyclingAssOrderAccountStatisticalVo vo = new RecyclingAssOrderAccountStatisticalVo();
        vo.setTotalFundQuota("0");
        vo.setTotalOrderNumber("0");

        SelectStatisticalDto selectStatisticalDto = this.baseMapper.selectStatistical(shopUserId);
        if (selectStatisticalDto == null) {
            return vo;
        }
        vo.setTotalFundQuota(selectStatisticalDto.getTotalFundQuota());
        vo.setTotalOrderNumber(selectStatisticalDto.getTotalOrderNumber());
        if (StrUtil.isNotBlank(shopUserId)) {
            vo.setRanking("0");
            Map<Long, HashMap> map = this.baseMapper.selectByAccountRanking(TenantContextHolder.getTenantId(), ShopContextHolder.getShopId());
            //获取用户排名
            HashMap o = map.get(Long.parseLong(shopUserId));
            if (o != null) {
                vo.setRanking(NumberUtil.roundStr((Double) o.get("rownum"), 0));
            }
        }
        return vo;
    }

    @Override
    public void removeRecyclingAssOrder(RecyclingAssOrder recyclingAssOrder, BigDecimal multiply,BigDecimal refundAmount) {
        RecyclingAssOrderAccount orderAccount = this.baseMapper.selectOne(
                new QueryWrapper<RecyclingAssOrderAccount>().eq("shop_user_id", recyclingAssOrder.getShopUserId())
        );
        if (orderAccount == null) {
            return;
        }
        if (recyclingAssOrder.getStatus() == 1){
            new RecyclingAssOrderAccount()
                    .setId(orderAccount.getId())
                    .setTotalFundQuota(orderAccount.getTotalFundQuota().subtract(multiply))
                    .setTotalAmount(orderAccount.getTotalAmount().subtract(refundAmount))
                    .updateById();
        }else {
            new RecyclingAssOrderAccount()
                    .setId(orderAccount.getId())
                    .setTotalFundQuota(orderAccount.getTotalFundQuota().subtract(recyclingAssOrder.getFundQuota()))
                    .setTotalAmount(orderAccount.getTotalAmount().subtract(recyclingAssOrder.getPayAmount()))
                    .setOrderNumber(orderAccount.getOrderNumber()-1)
                    .updateById();
        }

    }
}
